package com.mxz.auth.controller;

import com.mxz.auth.form.LoginBody;
import com.mxz.auth.form.RegisterBody;
import com.mxz.auth.service.SysLoginService;
import com.mxz.common.core.utils.JwtUtils;
import com.mxz.common.core.utils.StringUtils;
import com.mxz.common.core.web.domain.AjaxResult;
import com.mxz.common.security.auth.AuthUtil;
import com.mxz.common.security.service.TokenService;
import com.mxz.common.security.utils.SecurityUtils;
import com.mxz.common.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author mxz
 */
@RestController
@RequestMapping("/auth")
public class TokenController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody form) {
        // 用户登录
        return sysLoginService.login(form);
    }

    @DeleteMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return AjaxResult.success();
    }

    @PostMapping("/refresh")
    public AjaxResult refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
        }
        return AjaxResult.success();
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        return sysLoginService.register(registerBody);
    }
}
